package cn.lenchu.data.h2.dao;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lenchu.data.dao.GroupStockDao;
import cn.lenchu.data.h2.converter.GroupStockConverter;
import cn.lenchu.data.h2.entity.GroupStockEntity;
import cn.lenchu.data.h2.repository.GroupStockRepository;
import cn.lenchu.data.model.GroupStock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author lenchu
 */
@Service
public class GroupStockDaoImpl implements GroupStockDao {

    @Autowired
    private GroupStockRepository repository;

    @Override
    public List<GroupStock> listByGroupId(Integer groupId) {
        List<GroupStockEntity> groupStockEntityList = repository.findAllByGroupId(groupId);
        return groupStockEntityList.stream()
            .map(GroupStockConverter::toGroupStock)
            .collect(Collectors.toList());
    }

    @Override
    public GroupStock upsert(GroupStock groupStock) {
        if (groupStock == null) {
            return null;
        }
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        GroupStockEntity groupStockEntity = GroupStockConverter.toGroupStockEntity(groupStock);
        if (groupStock.getId() == null) {
            groupStockEntity.setCreateTime(now);
            groupStockEntity = repository.saveAndFlush(groupStockEntity);
            return GroupStockConverter.toGroupStock(groupStockEntity);
        } else {
            Optional<GroupStockEntity> entityOptional = repository.findById(groupStock.getId());
            if (entityOptional.isPresent()) {
                GroupStockEntity entity = entityOptional.get();
                BeanUtil.copyProperties(groupStockEntity, entity, CopyOptions.create().ignoreNullValue().ignoreError());
                entity.setUpdateTime(now);
                entity = repository.saveAndFlush(entity);
                return GroupStockConverter.toGroupStock(entity);
            }
        }
        return null;
    }

    @Override
    public GroupStock deleteById(Integer id) {
        Optional<GroupStockEntity> stockEntityOptional = repository.findById(id);
        if (stockEntityOptional.isPresent()) {
            GroupStockEntity groupStockEntity = stockEntityOptional.get();
            repository.deleteById(id);
            return GroupStockConverter.toGroupStock(groupStockEntity);
        }
        return null;
    }

    @Override
    public List<GroupStock> deleteByGroupId(Integer groupId) {
        List<GroupStockEntity> groupStockEntityList = repository.findAllByGroupId(groupId);
        repository.deleteAll(groupStockEntityList);
        return groupStockEntityList.stream()
            .map(GroupStockConverter::toGroupStock)
            .collect(Collectors.toList());
    }

}
